import 'dart:io';

import 'package:dio/dio.dart';
import 'package:edu/constants/config.dart';
import 'package:edu/networks/account/user_api.dart';
import 'package:edu/networks/business/business_api.dart';
import 'package:edu/networks/course/course_api.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/app_preferences.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/foundation.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

/*
 * 数据获取
 */
class DataFetcher {
  late final Dio dio;
  late final UserApi userApi = RemoteUserApi(dio);
  late final CourseApi courseApi = RemoteCourseApi(dio);
  late final BusinessApi businessApi = RemoteBusinessApi(dio);

  static final shared = DataFetcher._();
  DataFetcher._();

  Future<void> init() async {
    HttpOverrides.global = _MyHttpOverrides();
    dio = _buildDio();
  }

  /*用于更新请求授权令牌（Authorization Token）*/
  void updateAuthorizationToken(String? token) {
    if (token != null) {
      final headers = dio.options.headers;
      headers['authorization'] = 'Bearer $token';
      final options = dio.options.copyWith(headers: headers);
      dio.options = options;
    } else {
      final headers = dio.options.headers;
      headers.remove('authorization');
      final options = dio.options.copyWith(headers: headers);
      dio.options = options;
    }
  }

  // 构建 dio
  Dio _buildDio() {
    final dio = Dio();
    const timeOut = Duration(seconds: 60);
    final headers = <String, String>{
      'Content-Type': 'application/json',
      'accept': 'application/json',
    };

    // 添加token
    final token = AppPreferences.shared.userToken;
    if (token != null) {
      headers['authorization'] = 'Bearer $token';
    }

    // 配置 dio
    dio.options = BaseOptions(
      baseUrl: Config.baseUrl,
      connectTimeout: timeOut,
      receiveTimeout: timeOut,
      headers: headers,
      validateStatus: (status) {
        return true;
      },
    );

    // 添加拦截器
    if (kDebugMode) {
      dio.interceptors.add(
        PrettyDioLogger(
          // request: true,
          requestHeader: true,
          requestBody: true,
          // responseBody: true,
          responseHeader: true,
          // error: true,
        ),
      );
    }

    dio.interceptors.add(
      InterceptorsWrapper(
        onResponse: (response, handler) {
          final code = response.statusCode;
          if (code == 401) {
            // 登录过期, 登出
            AccountInfo.shared.logout();
            return handler.reject(
              DioException(
                requestOptions: response.requestOptions,
                response: response,
                error: '登录过期,请重新登录',
                message: '登录过期,请重新登录',
              ),
            );
          }
          return handler.next(response);
        },
        onError: (DioException error, handler) {
          final code = error.response?.statusCode;
          if (code == 401) {
            AccountInfo.shared.logout();
            return handler.reject(error);
          }
          Future.delayed(Duration.zero, () {
            AppRouter.shared.router.pushReplacement(AppRouter.kMainTab);
          });
          return handler.next(error);
        },
      ),
    );
    return dio;
  }
}

// 由于后端证书是自己生成的，防止过期
class _MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback = (X509Certificate cert, String host, int port) {
        return true;
      };
  }
}
